package initialize

import (
	"base/config"
	"base/global"
	"base/model"
	"gorm.io/gorm"
	"os"
)

type DbFactory struct{}

func (f *DbFactory) GetDB() (config.DBProvider, error) {
	switch global.Config.System.DbType {
	case "mysql":
		db := &global.Config.Mysql
		return db, nil
	case "pgsql":
		db := &global.Config.Pgsql
		return db, nil
	default:
		db := &global.Config.Mysql
		return db, nil
	}
}

func Gorm() (*gorm.DB, error) {
	df := &DbFactory{}
	db, err := df.GetDB()
	if err != nil {
		return nil, err
	}
	return db.Db()



	//var db config.DBProvider
	//switch global.Config.System.DbType {
	//case "mysql":
	//	db = &global.Config.Mysql
	//	return db.Db()
	//case "pgsql":
	//	db = &global.Config.Pgsql
	//	return db.Db()
	//default:
	//	db = &global.Config.Mysql
	//	return db.Db()
	//}
}

// DisConnectDB ...
func DisConnectDB() {
	//if err := global.DB.Close(); err != nil {
	//	log.Panicln("关闭数据库报错" + err.Error())
	//}
}

func DBMigrate() {
	err := global.DB.AutoMigrate(
		model.Todo{},
	)
	if err != nil {
		global.Logger.Error(err)
		os.Exit(0)
	}
	global.Logger.Info("register table success")
}
